<template>
	<view class="canvas-img-code">
		<canvas :style="{width:width+'px',height:height+'px','border-radius':'5px'}" canvas-id="imgcanvas" @error="canvasIdErrorCallback"></canvas>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				width: 73,
				height: 30,
				key: "",
				value: ""
			}
		},
		mounted: function() {
			var _self = this;
			setTimeout(function() {
				// this.init();
			}, 2000)
		},
		methods: {
			getCode() {
				var time = new Date().getTime();
				var data = {
					times: time
				}
				this.$api.apiPost('user/currency.user/GetVerification', data).then(res => {
					if (res.data.code == 200) {
						this.key = res.data.data.Verification_key;
						this.value = res.data.data.Verification_val;
						this.init();
					}
				})
			},
			init: function() {
				var context = uni.createCanvasContext('imgcanvas', this),
					w = this.width,
					h = this.height;
				context.setFillStyle("white");
				context.setLineWidth(5);
				context.fillRect(0, 0, w, h);
				var len = this.value+'';
				var arr = len.split('');
				for (var i = 0; i < arr.length; i++) {
					// var deg = this.rn(-30, 30); //字体的旋转角度
					context.setFontSize(20);
					context.setTextBaseline("top");
					context.setFillStyle(this.rc(40, 150));
					context.save();
					context.translate(15 * i + 15, parseInt(h / 1.5 + 10));
					// context.rotate(deg*Math.PI/180);
					context.fillText(arr[i], -4, -28);
					context.restore();
				}
				// uni.setStorage({
				// 	key: 'imgcode',
				// 	data: this.value
				// });
				// uni.setStorage({
				// 	key: 'codeKey',
				// 	data: this.key
				// });
				var data = {
					key: this.key,
					value: this.value
				}
				this.$emit("getValue", data);
				for (var i = 0; i < 40; i++) {
					context.beginPath();
					context.arc(this.rn(0, w), this.rn(0, h), 1, 0, 2 * Math.PI);
					context.closePath();
					context.setFillStyle(this.rc(150, 200));
					context.fill();
				}
				context.draw();
			},
			rc: function(min, max) {
				var r = this.rn(min, max);
				var g = this.rn(min, max);
				var b = this.rn(min, max);
				return "rgb(" + r + "," + g + "," + b + ")";
			},
			rn: function(max, min) {
				return parseInt(Math.random() * (max - min)) + min;
			},
			refresh: function() {
				this.getCode();
			},
			canvasIdErrorCallback: function(e) {
			}
		}
	}
</script>

<style lang="scss">
	.canvas-img-code {
		display: inline-block
	}
</style>
